package com.ranlen.ems_vue.service.serviceImpl;

import com.ranlen.ems_vue.dao.UserDao;
import com.ranlen.ems_vue.entity.User;
import com.ranlen.ems_vue.service.UserService;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Date;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    private UserDao userDao;

    @Autowired
    StringEncryptor encryptor;

    @Autowired
    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void register(User user) {
        User byUserName = userDao.findByUserName(user.getUsername());
        if (byUserName==null){
            user.setStatus("已激活");
            user.setRegisterTime(new Date());
            String psw = encryptor.encrypt(user.getPassword());
            user.setPassword(psw);
            userDao.save(user);
        }else {
            throw new RuntimeException("用户名已存在");
        }
    }

//    @Override
//    public User login(User user) {
//        //验证用户是否存在
//        User user1 = userDao.findByUserName(user.getUsername());
//        if (!ObjectUtils.isEmpty(user1)){
//            //验证密码
//            if (user1.getPassword().equalsIgnoreCase(user.getPassword())) {
//                return user1;
//            }else {
//                throw new RuntimeException("密码输入不正确");
//            }
//        }else {
//            throw new RuntimeException("用户名输入错误");
//        }
//    }
    @Override
    public User login(User user) {
        //验证用户是否存在
        User user1 = userDao.findByUserName(user.getUsername());
        if (!ObjectUtils.isEmpty(user1)){
            String psw = encryptor.decrypt(user1.getPassword());
            System.out.println(psw);
            //验证密码
            if (psw.equals(user.getPassword())) {
                return user1;
            }else {
                throw new RuntimeException("密码输入不正确");
            }
        }else {
            throw new RuntimeException("用户名输入错误");
        }
    }
}
